import Vue from 'vue';
import App from './App.vue';
import router from './router';
import './plugins/element.js';
import './plugins/echart';
import './plugins/tinymce';
import './assets/css/global.css';
// import './assets/font/iconfont.css'
import axios from 'axios';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { Message } from 'element-ui';

Vue.config.productionTip = false;
Vue.prototype.$axios = axios;
var msg = Message;
var routers = router;

//定义全局时间过滤器
Vue.filter('formatTime', function(value, form) {
    function dateFormat(date, format) {
        if (typeof date === "string") {
            var mts = date.match(/(\/Date\((\d+)\)\/)/);
            if (mts && mts.length >= 3) {
                date = parseInt(mts[2]);
            }
        }
        date = new Date(date);
        if (!date || date.toUTCString() == "Invalid Date") {
            return "";
        }
        var map = {
            "M": date.getMonth() + 1, //月份 
            "d": date.getDate(), //日 
            "h": date.getHours(), //小时 
            "m": date.getMinutes(), //分 
            "s": date.getSeconds(), //秒 
            "q": Math.floor((date.getMonth() + 3) / 3), //季度 
            "S": date.getMilliseconds() //毫秒 
        };

        format = format.replace(/([yMdhmsqS])+/g, function(all, t) {
            var v = map[t];
            if (v !== undefined) {
                if (all.length > 1) {
                    v = '0' + v;
                    v = v.substr(v.length - 2);
                }
                return v;
            } else if (t === 'y') {
                return (date.getFullYear() + '').substr(4 - all.length);
            }
            return all;
        });
        return format;
    }
    return dateFormat(value, form);
});


//设置全局API请求根路径
axios.defaults.baseURL = 'http://127.0.0.1:8888/api/private/v1';
//配置axios请求拦截器
axios.interceptors.request.use(function(config) {
    NProgress.start();
    //添加请求携带的token
    config.headers['Authorization'] = localStorage.getItem('token');
    return config;
}, function(err) {
    console.log(err);
});

//配置axios响应拦截器
axios.interceptors.response.use((res) => {
    NProgress.done();
    res = res.data;
    console.log(res);
    //检查token
    if (res.meta.status == 400 && res.meta.msg == '无效token') {
        localStorage.removeItem('token');
        return msg({
            message: res.meta.msg,
            type: 'error',
            duration: 1500,
            onClose: () => {
                routers.push('/login');
            }
        });
    }
    return res;
});

new Vue({
    router,
    render: h => h(App)
}).$mount('#app');